<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2018/6/6
 * Time: 16:16
 */

namespace app\api\controller\v2;

use app\common\lib\exception\ApiException;
use app\common\model\ArticleCategory;
use app\common\model\Article as ArticleModel;
use Exception;
use think\Cache;
use think\Db;
use think\response\Json;

/**
 * @title 文章相关接口
 * @desc 查看文章详情<br/>按页码获取文章列表，每页十条<br/>
 * @url /api/v2/article
 * @version 2.0.0
 * Class Article
 * @package app\api\controller\v2
 */
class Article extends Auth
{
    protected $restActionList = ['index', 'read'];

    /**
     * 获取文章分类
     * @return Json
     * @throws ApiException
     */
    public function category()
    {
        if (!request()->isGet()) {
            return show(config('code.error'), '未知操作', '', 403);
        }

        $category = (new ArticleCategory())->getArticleCategory();

        return show(config('code.success'), '文章分类加载成功', $category);
    }

    /**
     * 获取文章列表
     * @return Json
     */
    public function index()
    {
        if (!request()->isGet()) {
            return show(config('code.error'), '未知操作', '', 403);
        }

        $map = [
            'page' => input('get.page/d', 1),
            'cid' => input('get.cid/d'),
            'uid' => $this->user['id'],
            'uc_id' => $this->user['uc_id'],
        ];

        $data = (new ArticleModel())->getArticleList($map);

        return show(config('code.success'), '加载成功', $data);
    }

    /**
     * 未使用
     * @title 查看文章详情
     * @method GET
     * @return array
     */
    public function read()
    {
        if (!request()->isGet()) {
            return show(config('code.error'), '未知操作', '', 403);
        }

        $id = input('get.id/d');

        try {
            // 改变当前用户文章已读状态
            $where = ['uid' => $this->user['id'], 'aid' => $id];
            $aids = Db::table('app_user_article')->where($where)->field('aid')->find();

            // 删除文章阅读缓存
            Cache::rm('article_read_' . $this->user['id']);

            if (!$aids) {
                Db::table('app_user_article')->insert(['uid' => $this->user['id'], 'aid' => $id]);
            }

            $map['a.id'] = $id;
            $map['a.status'] = 1;
            $data = Db::table('wechatadmin.system_article')->alias('a')
                ->field('a.id,a.cid,a.title,u.author,u.avatar,a.publish_time,a.good,a.collect,a.read,a.content,c.name cname,at.name type_name,at.name_en type_name_en,a.introduction')
                ->join('wechatadmin.system_category c', 'a.cid=c.id', 'INNER')
                ->join('wechatadmin.system_admin_user u', 'a.uid=u.id', 'INNER')
                ->join('wechatadmin.system_article_type at', 'at.id=a.tid', 'LEFT')
                ->where($map)
                ->find();
            $data['publish_time'] = strtotime($data['publish_time']);
            $data['good'] += floor($data['read'] / 30);
            $data['collect'] += floor($data['read'] / 250);
            $data['good_status'] = false;
            $data['collect_status'] = false;
            $good = Db::table('wechatadmin.system_article_good')
                ->where(['aid' => $id, 'ucid' => $this->user['uc_id']])->find();

            $collect = Db::table('wechatadmin.system_article_collect')
                ->where(['aid' => $id, 'ucid' => $this->user['uc_id']])->find();

            if ($good != null)
            {
                $data['good_status'] = true;
            }
            if ($collect != null)
            {
                $data['collect_status'] = true;
            }
            // 文章查看次数+1 read
            Db::execute("UPDATE `wechatadmin`.`system_article`  SET `read`=`read`+1  WHERE  `id` = '$id'");

        }
        catch (Exception $e)
        {
            return show(config('code.error'), $e->getMessage());
        }
        return show(config('code.success'), '查看文章成功', $data);
    }

    /**
     * 获取文章评论
     * @return Json
     */
    public function comments()
    {
        if (!request()->isGet()) {
            return show(config('code.error'), '未知操作', '', 403);
        }
        $aids = input('get.aid/d');
        try {
            $data = Db::table('wechatadmin.system_article_comment')->alias('ac')
                ->field('ac.id,ac.aid,ac.content,ac.status,ac.create_time,ac.goods,ac.reply,u.nickname,u.avatar,ac.ucid,ra.sun,ra.moon,ra.asc')
                ->join('wechat_backup_07_18_14_43_00.app_user u', 'u.uc_id=ac.ucid', 'INNER')
                ->join('wechat_backup_07_18_14_43_00.app_recode r', 'r.uid=u.id', 'INNER')
                ->join('wechat_backup_07_18_14_43_00.app_recode_astro ra', 'ra.id=r.aid', 'INNER')
                ->where(['ac.aid' => $aids, 'ac.status' => 0, 'r.isself' => 1])
                ->order('ac.id DESC')
                ->paginate(10, false, ['query' => request()->param()])->toArray();
            $data_list = json_decode(json_encode($data), true);

            if (is_array($data_list['data']) && !empty($data_list['data'])) {
                foreach ($data_list['data'] as $k => $d) {
                    // 判断当前评论是否为自己的评论   前台显示删除按钮
                    if ($d['ucid'] == $this->user['uc_id'])
                    {
                        $data_list['data'][$k]['is_owner'] = true;
                    } else
                    {
                        $data_list['data'][$k]['is_owner'] = false;
                    }
                    unset($data_list['data'][$k]['ucid']);

                    $data_list['data'][$k]['good_status'] = false;
                    $good = Db::table('wechatadmin.system_comment_good')
                        ->where(['aid' => $aids, 'ucid' => $this->user['uc_id'], 'comment_id' => $d['id']])->find();

                    if ($good != null)
                    {
                        $data_list['data'][$k]['good_status'] = true;
                    }

                    $reply_list = Db::table('wechatadmin.system_comment_reply')->alias('cr')
                        ->field('cr.id,cr.content,cr.status,cr.create_time,cr.pid,cr.ucid,u.nickname nickname1,u2.nickname nickname2,u.avatar')
                        ->join('wechat_backup_07_18_14_43_00.app_user u', 'u.uc_id=cr.ucid', 'INNER')
                        ->join('wechatadmin.system_article_comment ac', 'ac.id=cr.comment_id', 'RIGHT')
                        ->join('wechat_backup_07_18_14_43_00.app_user u2', 'u2.uc_id=ac.ucid', 'INNER')
                        ->where(['cr.comment_id' => $d['id'], 'cr.status' => 0])
                        ->limit(3)
                        ->order('cr.id DESC')
                        ->select();

                    $reply_list = json_decode(json_encode($reply_list), true);

                    if (!empty($reply_list)) {
                        foreach ($reply_list as $k2 => $rl) {
                            if ($rl['pid'] != 0) {
                                // 上级的昵称
                                $new_nickname = Db::table('wechatadmin.system_comment_reply')
                                    ->alias('cr')
                                    ->join('wechat_backup_07_18_14_43_00.app_user u', 'u.uc_id=cr.ucid', 'INNER')
                                    ->field('nickname')
                                    ->where('cr.id', $rl['pid'])
                                    ->find();
                                $reply_list[$k2]['nickname2'] = $new_nickname['nickname'];
                            }
                        }
                    }

                    $data_list['data'][$k]['reply_list'] = $reply_list;
                }
                return show(200, '获取成功', $data_list);
            }

            $data_list['data'] = [];
            return show(200, '文章没有评论', $data_list);

        }
        catch (Exception $e)
        {
            return show(config('code.error'), $e->getMessage(), [], 500);
        }

    }

    /**
     * 参数规则
     * @return array
     */
    public static function getRules()
    {
        $rules = [
            'index' => [
                'cid' => ['name' => 'cid', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '栏目id', 'range' => '星文推荐为1',],
                'page' => ['name' => 'page', 'type' => 'int', 'require' => 'false', 'default' => '1', 'desc' => '页码', 'range' => '',],
            ],
            'read' => [
                'id' => ['name' => 'id', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '文章id', 'range' => '',],
            ],
        ];
        return $rules;
    }
}